//
//  NetWorkManager.swift
//  FirstSwiftApp
//
//  Created by weijieMac on 2018/8/22.
//  Copyright © 2018年 Mac. All rights reserved.
//

import Foundation
import Moya
import Alamofire


func manager() -> Alamofire.SessionManager {
    let configuration = URLSessionConfiguration.default
    configuration.timeoutIntervalForRequest = 5 // timeout
    configuration.timeoutIntervalForResource = 5
    let manager = Alamofire.SessionManager(configuration: configuration);
    return manager
}

let networkManager = MoyaProvider<NetworkManager>(manager: manager())

//let HostIP = "http://192.168.1.120:8001"
let HostIP = "http://192.168.0.1"

let deviceId = UIDevice.current.identifierForVendor!.uuidString

fileprivate enum Method: String {
    
    case get_cmd = "goform/goform_get_cmd_process"
    case set_cmd = "goform/goform_set_cmd_process"
    
}

enum NetworkManager {

    case get_cmd()
    case login(password:String)
    case logout()
    case getDeviceInfo()//获取硬件信息
    case connect()
    case restartDevice()
    case getDevices()//获取连接到硬件的手机信息
    case getDeviceInfoList()//设置页面,获取设备信息接口
    case getNetMode()
    case setNetMode(mode:Int)
    case setDisconnet()//断开设备链接
    case setNetConnectModel(connectMode:String,roamMode:String)
    case setNetRoamModel(connectMode:String,roamMode:String)
    case setWifiReSetTime(time:String)
    case setMessageReaded(msg_id:String)
    case getwifiTime()//获取wifi休眠时间
    case setSSID(ssid:String,broadcast:String,secureMode:String,pwd:String,max:String,cipher:String,shared:String)
    case setWPS(mode:String,pin:String?,ssid:String)
    case getACLMode()
    case setACLMode(aclmode:String,blackList:String,whiteList:String)
    case updateAccount(newPassword:String,newAccount:String)
    case updatePassword(newPassword:String,newAccount:String)
    case setPinSwitch(status:Bool,code:String)
    case restoreFactory()
    case setLimitData(limitSwitch:String, unit:String, size:String, percent:String)
    case getSMSList()
    case deleteSMS(id:String)
    case getUSSDFlag()
    case sendSMS(number:String,message:String)
    case sendUSSD(number:String)
}

extension NetworkManager: TargetType {
    var headers: [String : String]? {
        return ["Host":"192.168.0.1","Referer":"http://192.168.0.1/index.html"]
    }
    
    /// The target's base `URL`.
    var baseURL: URL {
        return URL(string: HostIP)!
    }
    
    /// The path to be appended to `baseURL` to form the full `URL`.
    var path: String {
        
        switch self {
        case .login(_),
             .connect(),
             .logout(),
             .restartDevice(),
             .setNetConnectModel(_, _),
             .setNetRoamModel(_,_ ),
             .setWifiReSetTime(_),
             .setMessageReaded(_),
             .setSSID(_,_,_,_,_,_,_),
             .setWPS(_,_,_),
             .setACLMode(_,_,_),
             .updateAccount(_,_),
             .updatePassword(_,_),
             .setPinSwitch(_,_),
             .restoreFactory(),
             .setLimitData(_,_,_,_),
             .deleteSMS(_),
             .sendSMS(_,_),
             .setNetMode(_),
             .setDisconnet(),
             .sendUSSD(_):
            return Method.set_cmd.rawValue
        case .get_cmd(),
             .getDeviceInfo(),
             .getDevices(),
             .getDeviceInfoList(),
             .getACLMode(),
             .getNetMode(),
             .getSMSList(),
             .getwifiTime(),
             .getUSSDFlag():
            return Method.get_cmd.rawValue
        default :
            return ""
        }
    }
    
    /// The HTTP method used in the request.
    var method: Moya.Method {
        switch self {
        case .getDeviceInfoList(),
             .getACLMode(),
             .getNetMode(),
             .getwifiTime(),
             .setNetMode(_),
             .setDisconnet(),
             .setPinSwitch(_,_),
             .getDevices(),
             .getSMSList():
            return .get
        default:
            return .post
        }
    }
    
    /// The parameters to be encoded in the request.
    var parameters: [String: Any]? {
        switch self {
        case .login(let password):
            return ["goformId":"LOGIN","password":password,"isTest":"0"]
        case .logout():
            return ["goformId":"LOGOUT","isTest":"0"]
        case .getDeviceInfoList():
            return ["goformId":"GET_DEVICE_INFO",
                    "isTest":"0", "multi_data":"1&sms_received_flag_flag=0&sts_received_flag_flag=0&isTest=0&cmd=wifi_coverage,m_ssid_enable,imei,web_version,wa_inner_version,hardware_version,MAX_Access_num,SSID1,m_SSID,m_HideSSID,m_MAX_Access_num,lan_ipaddr,mac_address,msisdn,LocalDomain,wan_ipaddr,pdp_type,ppp_status,sim_imsi,roam_setting_option,dial_mode,RadioOff,wifi_coverage,sysIdleTimeToSleep,security_mode,AuthMode,HideSSID,EncrypType,WPAPSK1_encode,wps_mode,WPS_SSID"]
        case .restartDevice():
            return ["goformId":"REBOOT_DEVICE","isTest":"0"]
        case .restoreFactory():
            return ["goformId":"RESTORE_FACTORY_SETTINGS","isTest":"0"]
        case .connect():
            return ["goformId":"CONNECT_NETWORK","isTest":"0"]
        case .getDeviceInfo():
            return ["isTest":"0",
                    "sms_received_flag_flag":"0",
                    "sts_received_flag_flag":"0",
                    "multi_data":"1",
        "cmd":"sim_iccid,modem_main_state,pin_status,loginfo,new_version_state,current_upgrade_state,is_mandatory,sms_received_flag,sts_received_flag,signalbar,network_type,network_provider,ppp_status,EX_SSID1,sta_ip_status,EX_wifi_profile,m_ssid_enable,sms_unread_num,RadioOff,simcard_roam,lan_ipaddr,station_mac,battery_charging,battery_vol_percent,battery_pers,spn_display_flag,plmn_display_flag,spn_name_data,spn_b1_flag,spn_b2_flag,realtime_tx_bytes,realtime_rx_bytes,realtime_time,realtime_tx_thrpt,realtime_rx_thrpt,monthly_rx_bytes,monthly_tx_bytes,monthly_time,date_month,data_volume_limit_switch,data_volume_limit_size,data_volume_alert_percent,data_volume_limit_unit,roam_setting_option,upg_roam_switch,SSID1,HTTP_SHARE_WR_AUTH,HTTP_SHARE_STATUS,AuthMode,sdcard_mode_option,sd_card_state,HTTP_SHARE_CARD_USER,HTTP_SHARE_FILE,pinnumber"]
        case .getDevices():
            return ["isTest":"0","cmd":"station_list"]
        case .setNetConnectModel(let connectMode, let roamMode):
            return ["isTest":"0",
                    "goformId": "SET_CONNECTION_MODE",
                    "ConnectionMode": connectMode,
                    "roam_setting_option":roamMode]
        case .setNetRoamModel(let connectMode, let roamMode):
            return ["isTest":"0",
                    "goformId": "SET_NET_ROAM_MODE",
                    "ConnectionMode": connectMode,
                    "roam_setting_option":roamMode]
        case .setWifiReSetTime(let time):
            return ["isTest":"0",
                    "goformId":"SET_WIFI_SLEEP_INFO",
                    "sysIdleTimeToSleep":time]
        case .setMessageReaded(let msg_id):
            return ["isTest":"0",
                    "goformId":"SET_MSG_READ",
                    "tag":"0",
                    "msg_id":msg_id]
            
        case .getwifiTime():
            return ["isTest":"0",
                    "cmd":"Sleep_interval"]
        case .setSSID(let ssid,let broadcast,let secureMode,let pwd,let max,let cipher,let shared):
            return ["isTest":"0",
                    "goformId":"SET_WIFI_SSID1_SETTINGS",
                    "ssid":ssid,
                    "broadcastSsidEnabled":broadcast,
                    "MAX_Access_num":max,
                    "security_mode":secureMode,
                    "cipher":cipher,
                    "security_shared_mode":shared,
                    "passphrase":pwd]
        case .setWPS(let mode,let pin,let ssid):
            var params = ["isTest":"0",
                          "goformId":"WIFI_WPS_SET",
                          "wps_mode":mode,
                          "WPS_SSID":ssid]
            if pin != nil {
                params["wps_pin"] = pin!
            }
            return params
        case .getACLMode():
            return ["isTest":"false",
                    "multi_data":"1",
                    "cmd":"ACL_mode,wifi_mac_black_list,wifi_mac_white_list"]
        case .setACLMode(let aclmode,let blackList,let whiteList):
            
            var params =  ["isTest":"0",
                           "goformId":"WIFI_MAC_FILTER",
                           "ACL_mode":aclmode]
                         
            
            if !blackList.isEmpty {
                 params["wifi_mac_black_list"] = blackList
            }
            if !whiteList.isEmpty {
                params["wifi_mac_white_list"] = whiteList
            }
            
            return params
        case .getNetMode():
            return ["cmd":"net_select",
                    "multi_data":"1"]
        case .setDisconnet():
            return ["goformId":"DISCONNECT_NETWORK"]
        case .setNetMode(let mode):
            var modestr = ""
            switch mode {
            case 0:
                modestr = "NETWORK_auto"
            case 1:
                modestr = "Only_LTE"
            case 2:
                modestr = "Only_WCDMA"
            case 3:
                modestr = "Only_GSM"
            default:
                break
            }
            return ["BearerPreference":modestr,"goformId":"SET_BEARER_PREFERENCE"
                    ]
        case .updateAccount(let newPassword,let newAccount):
            return ["isTest":"0",
                    "goformId":"CHANGE_ACCOUNT",
                    "newPassword":newPassword,
                    "newUserName":newAccount]
        case .updatePassword(let newPassword,let newAccount):
            return ["isTest":"0",
                    "goformId":"CHANGE_ACCOUNT",
                    "newPassword":newPassword,
                    "newUserName":newAccount]
        case .setPinSwitch(let status,let code):
            return [
                    "goformId":(status ? "ENABLE_PIN": "DISABLE_PIN"),
                    "OldPinNumber":code]
        case .setLimitData(let limitSwitch,let unit,let size,let percent):
            return ["isTest":"0",
                    "goformId": "DATA_LIMIT_SETTING",
                    "data_volume_limit_switch":limitSwitch,
                    "data_volume_limit_unit":unit,
                    "data_volume_limit_size":size,
                    "data_volume_alert_percent":percent]
        case .getSMSList():
            return ["isTest":"false",
                    "cmd":"sms_data_total",
                    "page":"0",
                    "data_per_page":"2000",
                    "mem_store":"2",
                    "tags":"10",
                    "order_by":"order+by+id+asc"]
        case .deleteSMS(let id):
            return ["isTest":"false",
                    "goformId":"DELETE_SMS",
                    "notCallback":"true",
                    "msg_id":id]
        case .getUSSDFlag():
            return ["cmd":"ussd_write_flag",
                    "_":"\(Int(Date().timeIntervalSince1970))"]
        case .sendSMS(let number,let message):
            return ["isTest":"false",
                    "goformId":"SEND_SMS",
                    "notCallback":"true",
                    "Number":number,
                    "sms_time":getCurrentTime(),
                    "MessageBody":message,
                    "ID":"-1",
                    "encode_type":"UNICODE"]
        case .sendUSSD(let number):
            return ["isTest":"false",
                    "goformId":"USSD_PROCESS",
                    "USSD_operator":"ussd_send",
                    "USSD_send_number":number,
                    "notCallback":"true"]
        default:
            break
        }
        return nil
    }
    
    /// The method used for parameter encoding.
    var parameterEncoding: ParameterEncoding {
        return URLEncoding.default
    }
    
    /// Provides stub data for use in testing.
    var sampleData: Data {
        return "".data(using: .utf8)!
    }
    
    /// The type of HTTP task to be performed.
    var task: Task {
        if parameters != nil {
            return .requestParameters(parameters: parameters!, encoding: URLEncoding.default)
        }else {
            return .requestPlain
        }
    }
    
    /// Whether or not to perform Alamofire validation. Defaults to `false`.
    
    var validationType: ValidationType {
        return .none
    }
    
    func getCurrentTime() -> String {
        let format = DateFormatter()
        format.dateFormat = "yy;MM;dd;HH;mm;ss;zzz"
        return format.string(from: Date())
    }
    
}



